package com.eshop.modules.mp.service;

import org.slf4j.LoggerFactory;
import java.lang.invoke.SerializedLambda;
import com.eshop.modules.user.service.dto.WechatUserDto;
import java.io.Serializable;
import com.eshop.modules.user.domain.ShopUser;
import com.eshop.enums.ShopCommonEnum;
import com.eshop.api.EshopException;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.eshop.modules.mp.domain.WechatTemplate;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.common.error.WxErrorException;
import com.eshop.modules.mp.config.WxMpConfiguration;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import com.eshop.utils.RedisUtil;
import com.eshop.utils.ShopKeyUtils;
import java.util.Map;
import com.eshop.modules.mp.enums.WechatTempateEnum;
import java.util.HashMap;
import cn.hutool.core.util.StrUtil;
import com.eshop.modules.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import com.eshop.utils.RedisUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class WeixinTemplateService
{
    private static final Logger log;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private WechatTemplateService wechatTemplateService;
    
    public void rechargeSuccessNotice(final String time, final String price, final Long uid) {
        final String openid = this.getUserOpenid(uid);
        if (StrUtil.isBlank((CharSequence)openid)) {
            return;
        }
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", "您的账户金币发生变动，详情如下：");
        map.put("keyword1", "充值");
        map.put("keyword2", time);
        map.put("keyword3", price);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.RECHARGE_SUCCESS.getValue());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            this.sendWxMpTemplateMessage(openid, tempId, this.getSiteUrl() + "/user/account", map);
        }
    }
    
    public void paySuccessNotice(final String orderId, final String price, final Long uid) {
        final String openid = this.getUserOpenid(uid);
        if (StrUtil.isBlank((CharSequence)openid)) {
            return;
        }
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", "您的订单已支付成功，我们会尽快为您发货。");
        map.put("keyword1", orderId);
        map.put("keyword2", price);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.PAY_SUCCESS.getValue());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            this.sendWxMpTemplateMessage(openid, tempId, this.getSiteUrl() + "/order/detail/" + orderId, map);
        }
    }
    
    public void paySuccessNoticeToKefu(final String orderId, final String price, final String openId) {
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", "尊敬的客服,您有新订单了");
        map.put("keyword1", orderId);
        map.put("keyword2", price);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.PAY_SUCCESS.getValue());
        final String appId = (String)RedisUtil.get(ShopKeyUtils.getWxAppAppId());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            if (StrUtil.isBlank((CharSequence)appId)) {
                this.sendWxMpTemplateMessage(openId, tempId, this.getSiteUrl() + "/order/detail/" + orderId, map);
            }
            else {
                final WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
                miniProgram.setAppid((String)RedisUtil.get(ShopKeyUtils.getWxAppAppId()));
                miniProgram.setPagePath("pages/orderAdmin/AdminOrder/index?oid=" + orderId);
                this.sendWxMpTemplateMessageToWx(openId, tempId, miniProgram, map);
            }
        }
    }
    
    public void refundSuccessNotice(final String title, final String orderId, final String price, final Long uid, final String time) {
        final String openid = this.getUserOpenid(uid);
        if (StrUtil.isBlank((CharSequence)openid)) {
            return;
        }
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", title);
        map.put("keyword1", orderId);
        map.put("keyword2", price);
        map.put("keyword3", time);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.REFUND_SUCCESS.getValue());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            this.sendWxMpTemplateMessage(openid, tempId, this.getSiteUrl() + "/order/detail/" + orderId, map);
        }
    }
    
    public void refundSuccessNoticeToKefu(final String title, final String orderId, final String price, final String openId, final String time) {
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", title);
        map.put("keyword1", orderId);
        map.put("keyword2", price);
        map.put("keyword3", time);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.REFUND_SUCCESS.getValue());
        final String appId = (String)RedisUtil.get(ShopKeyUtils.getWxAppAppId());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            if (StrUtil.isBlank((CharSequence)appId)) {
                this.sendWxMpTemplateMessage(openId, tempId, this.getSiteUrl() + "/order/detail/" + orderId, map);
            }
            else {
                final WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
                miniProgram.setAppid((String)RedisUtil.get(ShopKeyUtils.getWxAppAppId()));
                miniProgram.setPagePath("pages/orderAdmin/AdminOrder/index?oid=" + orderId);
                this.sendWxMpTemplateMessageToWx(openId, tempId, miniProgram, map);
            }
        }
    }
    
    public void deliverySuccessNotice(final String orderId, final String deliveryName, final String deliveryId, final Long uid) {
        final String openid = this.getUserOpenid(uid);
        if (StrUtil.isEmpty((CharSequence)openid)) {
            return;
        }
        final Map<String, String> map = new HashMap<String, String>();
        map.put("first", "亲，宝贝已经启程了，好想快点来到你身边。");
        map.put("keyword2", deliveryName);
        map.put("keyword1", orderId);
        map.put("keyword3", deliveryId);
        map.put("remark", "yshop为您服务！");
        final String tempId = this.getTempId(WechatTempateEnum.DELIVERY_SUCCESS.getValue());
        if (StrUtil.isNotBlank((CharSequence)tempId)) {
            this.sendWxMpTemplateMessage(openid, tempId, this.getSiteUrl() + "/order/detail/" + orderId, map);
        }
    }
    
    private String sendWxMpTemplateMessage(final String openId, final String templateId, final String url, final Map<String, String> map) {
        final WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().toUser(openId).templateId(templateId).url(url).build();
        map.forEach((k, v) -> templateMessage.addData(new WxMpTemplateData(k, v, "#000000")));
        String msgId = null;
        final WxMpService wxService = WxMpConfiguration.getWxMpService();
        try {
            msgId = wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        }
        catch (WxErrorException e) {
            e.printStackTrace();
        }
        return msgId;
    }
    
    public String sendWxMpTemplateMessageToWx(final String openId, final String templateId, final WxMpTemplateMessage.MiniProgram miniProgram, final Map<String, String> map) {
        final WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().toUser(openId).templateId(templateId).miniProgram(miniProgram).build();
        map.forEach((k, v) -> templateMessage.addData(new WxMpTemplateData(k, v, "#000000")));
        String msgId = null;
        final WxMpService wxService = WxMpConfiguration.getWxMpService();
        try {
            msgId = wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        }
        catch (WxErrorException e) {
            WeixinTemplateService.log.error(e.getMessage(), (Throwable)e);
        }
        return msgId;
    }
    
    private String getTempId(final String key) {
        final WechatTemplate wechatTemplate = (WechatTemplate)((this.wechatTemplateService.lambdaQuery().eq(WechatTemplate::getType, "template")).eq(WechatTemplate::getTempkey, key)).one();
        if (wechatTemplate == null) {
            throw new EshopException("请后台配置key:" + key + "模板消息id");
        }
        if (ShopCommonEnum.IS_STATUS_0.getValue().equals(wechatTemplate.getStatus())) {
            return "";
        }
        return wechatTemplate.getTempid();
    }
    
    private String getSiteUrl() {
        final String apiUrl = this.redisUtils.getY(ShopKeyUtils.getSiteUrl());
        if (StrUtil.isBlank((CharSequence)apiUrl)) {
            return "";
        }
        return apiUrl;
    }
    
    private String getUserOpenid(final Long uid) {
        final ShopUser shopUser = (ShopUser)this.userService.getById((Serializable)uid);
        if (shopUser == null) {
            return "";
        }
        final WechatUserDto wechatUserDto = shopUser.getWxProfile();
        if (wechatUserDto == null) {
            return "";
        }
        if (StrUtil.isBlank((CharSequence)wechatUserDto.getOpenid())) {
            return "";
        }
        return wechatUserDto.getOpenid();
    }
    
    static {
        log = LoggerFactory.getLogger((Class)WeixinTemplateService.class);
    }
}
